package com.zsh.rabbitmq.eight;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.zsh.rabbitmq.utils.RabbitMQUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zsh
 * @Description 死信队列实战，消费者1
 * @create 2022-05-06 10:11
 */
public class Consumer01 {
    public static final String NORMAL_EXCHANGE = "normal_exchange";
    public static final String DEAD_EXCHANGE = "dead_exchange";
    public static final String NORMAL_QUEUE = "normal_queue";
    public static final String DEAD_QUEUE = "dead_queue";

    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMQUtils.getChannel();

        //声明交换机，普通 and 死信
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);

        //普通队列，需要填入参数
        Map<String, Object> arguments = new HashMap<>();
        //过期时间
        //arguments.put("x-message-ttl",10000); //发送者也可以设置消息过期时间
        //过期转发至死信交换机
        arguments.put("x-dead-letter-exchange",DEAD_EXCHANGE);
        //设置交换机到队列的路由
        arguments.put("x-dead-letter-routing-key","lisi");
        //队列长度限制
        //arguments.put("x-max-length",6);
        channel.queueDeclare(NORMAL_QUEUE,false,false,false,arguments);

        //死信队列
        channel.queueDeclare(DEAD_QUEUE,false,false,false,null);

        //绑定交换机和队列
        channel.queueBind(NORMAL_QUEUE,NORMAL_EXCHANGE,"zhangsan");
        channel.queueBind(DEAD_QUEUE,DEAD_EXCHANGE,"lisi");

        System.out.println("c1等待接收消息......");

        //接收消息
        DeliverCallback deliverCallback = (consumerTag, message) ->{
            String msg = new String(message.getBody(),"UTF-8");
            if (msg.equals("info5")){
                System.out.println("c1 拒收的消息是：" + msg);
                channel.basicReject(message.getEnvelope().getDeliveryTag(),false);
            }else {
                System.out.println("c1 接收到的消息是：" + msg);
                channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
            }

        };

        channel.basicConsume(NORMAL_QUEUE,false,deliverCallback,consumerTag ->{});
    }
}
